package com.iframework.anson;

import java.util.List;

import com.iframework.model.json.Books;
import com.iframework.tools.BaseTools;
import com.iframework.tools.DBHelp_JDBC_MySQL;

public class BookManagerTheard implements Runnable {
	// 表名
	private String tabName = "tbl_book";
	// 表字段
	private String[] tab_fields = { "_id", "title", "categrouy", "author", "site", "cover", "shortIntro", "banned",
			"latelyFollower", "latelyFollowerBase", "retentionRatio", "minRetentionRatio", "RankingId", "created" };
	private String[] u_fields = { "title", "categrouy", "author", "site", "cover", "shortIntro", "banned",
			"latelyFollower", "latelyFollowerBase", "retentionRatio", "minRetentionRatio", "RankingId", "updated" };
	private String[] q_fields = { "_id" };
	private String strNowTime = BaseTools.getNow();
	private Books book;
	private String rankingId;
	private List<Books> bookList;
	private DBHelp_JDBC_MySQL db;
	// 增加标志位，用来实现线程的挂起和恢复
	private volatile boolean suspended;
	// volatile关键字，表示该变量可能在被一个线程使用的同时，被另一个线程修改
	private volatile int firstVal;
	private volatile int secondVal;

	public BookManagerTheard(DBHelp_JDBC_MySQL db,String rankingId, List<Books> bookList) {
		this.db=db;
		this.rankingId = rankingId;
		this.bookList = bookList;
	}

	// 判断二者是否相等
	public boolean areValuesEqual() {
		return (firstVal == secondVal);
	}

	// 赋值后，休眠300毫秒，从而使线程有机会在stepOne操作和stepTwo操作之间被挂起
	private void stepOne(int newVal) throws InterruptedException {
		firstVal = newVal;
		Thread.sleep(300); // 模拟长时间运行的情况
	}

	private void stepTwo(int newVal) {
		secondVal = newVal;
	}

	public void suspendRequest() {
		suspended = true;
	}

	public void resumeRequest() {
		suspended = false;
	}

	private void waitWhileSuspended() throws InterruptedException {

		// 这是一个“繁忙等待”技术的示例。
		// 它是非等待条件改变的最佳途径，因为它会不断请求处理器周期地执行检查，
		// 更佳的技术是：使用Java的内置“通知-等待”机制
		while (suspended) {
			Thread.sleep(200);
		}
	}

	@Override
	public void run() {
		try {
			firstVal = 0;
			secondVal = 0;
			workMethod();
		} catch (InterruptedException x) {
			System.out.println("interrupted while in workMethod()");
		}
	}

	public void workMethod() throws InterruptedException {
		int val = 1;
		while (bookList.iterator().hasNext()) {
			book = bookList.get(0);
			String[] q_data = { book.get_id() };
			String[] q_result = DBHelp_JDBC_MySQL.query(tabName, q_fields, q_data, q_fields);
			if (q_result == null || q_result.length == 0 || (q_result.length == 1 && q_result[0] == null)) {
				// BaseTools.log("新增书籍 "+book.getTitle());
				String[] data = { book.get_id(), book.getTitle(), book.getCat(), book.getAuthor(), book.getSite(),
						book.getCover(), book.getShortIntro(), String.valueOf(book.getBanned()),
						String.valueOf(book.getLatelyFollower()), String.valueOf(book.getLatelyFollowerBase()),
						book.getRetentionRatio(), String.valueOf(book.getMinRetentionRatio()), rankingId, strNowTime };
				db.insert(tabName, tab_fields, data,book.getTitle());
			} else {
				// BaseTools.log("更新书籍 "+book.getTitle());
				String[] u_data = { book.getTitle(), book.getCat(), book.getAuthor(), book.getSite(), book.getCover(),
						book.getShortIntro(), String.valueOf(book.getBanned()),
						String.valueOf(book.getLatelyFollower()), String.valueOf(book.getLatelyFollowerBase()),
						book.getRetentionRatio(), String.valueOf(book.getMinRetentionRatio()), rankingId, strNowTime };
				db.update(tabName, u_fields, u_data, q_fields, q_data,book.getTitle());
			}
			q_result = db.query(tabName, q_fields, q_data, new String[] { "id" });
			BookManager.BookSourceManager(q_result[0],book.get_id(),book.getTitle());
			// BaseTools.log("---->线程分隔符<----");
			bookList.remove(book);

			// 仅当线程挂起时，才运行这行代码
			waitWhileSuspended();

			stepOne(val);
			stepTwo(val);
			val++;

			// 仅当线程挂起时，才运行这行代码
			waitWhileSuspended();

			Thread.sleep(200);

		}

	}
}
